import 'dart:io';

import 'package:flutter/material.dart';
import 'package:ohos_flutter_photoviewpicker/photoPicker.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var id;
  Future<Map<Object?, Object?>>? _loadPhoto;
  final List<Widget> list = <Widget>[];

  Future<Widget> buildThumbnail(path) async {
    return Image.file(
      File(path),
      fit: BoxFit.cover,
      filterQuality: FilterQuality.high,
      width: 100,
      height: 100,
    );
  }

  Widget getGridView(BuildContext context, AsyncSnapshot<Map<Object?, Object?>> snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasData) {
        final Map combined = snapshot.data!;
        combined.forEach((key, value) async {
          Widget widget = await buildThumbnail(value);
          list.add(widget);
        });
      }
    }
    return Expanded(
      child: GridView(
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 1.0,
        ),
        children: [...list],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: ElevatedButton(
                    child: const Text('打开图库'),
                    onPressed: () async {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => const PhotoPickerPage()),
                      ).then((value) {
                        setState(() {
                          list.clear();
                          _loadPhoto = new Future(() => value);
                          Future.delayed(Duration(milliseconds: 100), () {
                            setState(() {});
                          });
                        });
                      });

                    },
                  ),
                ),
              ],
            ),
            FutureBuilder<Map<Object?, Object?>>(
              future: _loadPhoto,
              builder: getGridView,
            ),
          ],
        ),
      ),
    );
  }
}
